import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import HomePage from '../pages/HomePage.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: HomePage
  },
  {
    path: '/table-board',
    name: 'TableBoard',
    component: () => import(/* webpackChunkName: "table-board" */ /* webpackPrefetch: true */ '../pages/TableBoard.vue')
  },
  {
    path: '/bucket-board',
    name: 'BucketBoard',
    component: () => import(/* webpackChunkName: "bucket-board" */ /* webpackPrefetch: true */ '../pages/BucketBoard.vue')
  },
  {
    path: '/favorites-board',
    name: 'FavoritesBoard',
    component: () => import(/* webpackChunkName: "favorites-board" */ /* webpackPrefetch: true */ '../pages/FavoritesBoard.vue')
  },
  {
    path: '/trash-bin',
    name: 'TrashBin',
    component: () => import(/* webpackChunkName: "trash-bin" */ /* webpackPrefetch: true */ '../pages/TrashBin.vue')
  },
  {
    path: '/editor',
    name: 'CardEditor',
    component: () => import(/* webpackChunkName: "card-editor" */ /* webpackPrefetch: true */ '../pages/CardEditor.vue')
  },
  {
    path: '/editor/:id',
    name: 'EditCard',
    component: () => import(/* webpackChunkName: "card-editor" */ /* webpackPrefetch: true */ '../pages/CardEditor.vue')
  },
  {
    path: '/card/:id',
    name: 'ViewCard',
    component: () => import(/* webpackChunkName: "view-card" */ /* webpackPrefetch: true */ '../pages/ViewCard.vue')
  },
  {
    path: '/settings',
    name: 'Settings',
    component: () => import(/* webpackChunkName: "settings" */ /* webpackPrefetch: true */ '../pages/Settings.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() {
    return { top: 0 } // 页面切换时滚动到顶部
  }
})

// 全局路由预加载
const preloadRoutes = () => {
  routes.forEach(route => {
    // 检查并只预加载懒加载的组件
    if (typeof route.component === 'function' && route.name !== 'Home') {
      // 使用类型断言确保可调用
      const lazyLoadFn = route.component as () => Promise<any>
      lazyLoadFn()
    }
  })
}

// 应用启动后开始预加载
setTimeout(preloadRoutes, 1000)

export default router